package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.common.Result;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户中心控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserCenterController {
    
    @Autowired
    private UserCollectionService userCollectionService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private OrderItemService orderItemService;
    
    @Autowired
    private UserAddressService userAddressService;
    
    @Autowired
    private ContentService contentService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private AcupointCategoryService acupointCategoryService;
    
    @Autowired
    private LoginUserService loginUserService;
    
    // ==================== 用户收藏功能接口 ====================
    
    /**
     * 获取用户收藏列表
     */
    @GetMapping("/collections")
    public Result<Map<String, Object>> getUserCollections(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            List<UserCollection> collections = userCollectionService.list(queryWrapper);

            List<Map<String, Object>> resultList = collections.stream().map(collection -> {
                Map<String, Object> item = new HashMap<>();
                item.put("id", collection.getId());
                item.put("entityType", collection.getEntityType());
                item.put("entityId", collection.getEntityId());
                item.put("collectTime", collection.getCollectTime());

                // 根据收藏类型获取详细信息
                if ("course".equals(collection.getEntityType())) {
                    Content content = contentService.getById(collection.getEntityId());
                    if (content != null) {
                        item.put("title", content.getTitle());
                        item.put("cover", content.getCover());
                        item.put("intro", content.getIntro());
                        item.put("price", content.getPrice());
                        item.put("isFree", content.getIsFree() == 1);
                        item.put("duration", content.getDuration());
                        item.put("viewCount", content.getViewCount());
                    }
                } else if ("product".equals(collection.getEntityType())) {
                    Product product = productService.getById(collection.getEntityId());
                    if (product != null) {
                        item.put("title", product.getName());
                        item.put("cover", product.getCover());
                        item.put("intro", product.getIntro());
                        item.put("price", product.getPrice());
                        item.put("isFree", false);
                    }
                } else if ("acupoint".equals(collection.getEntityType())) {
                    AcupointCategory acupoint = acupointCategoryService.getById(collection.getEntityId());
                    if (acupoint != null) {
                        item.put("title", acupoint.getCategoryName());
                        item.put("intro", acupoint.getDescription());
                        item.put("price", 0);
                        item.put("isFree", true);
                    }
                }
                return item;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("collections", resultList);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户收藏失败", e);
            return Result.error("获取用户收藏失败");
        }
    }
    
    /**
     * 取消收藏
     */
    @PostMapping("/collections/remove")
    public Result<Map<String, Object>> removeCollection(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        Long entityId = Long.valueOf(request.get("entityId").toString());
        String entityType = (String) request.get("entityType");

        if (entityId == null || entityType == null) {
            return Result.badRequest("参数不能为空");
        }

        try {
            QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                       .eq("entity_id", entityId)
                       .eq("entity_type", entityType);
            
            boolean success = userCollectionService.remove(queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("entityId", entityId);
            data.put("entityType", entityType);
            data.put("message", success ? "取消收藏成功" : "取消收藏失败");
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return Result.error("取消收藏失败");
        }
    }
    
    // ==================== 用户订单功能接口 ====================
    
    /**
     * 获取用户订单列表
     */
    @GetMapping("/orders")
    public Result<Map<String, Object>> getUserOrders(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            log.info("查询用户 {} 的订单列表", userId);
            
            // 使用QueryWrapper查询指定用户的订单
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                       .orderByDesc("create_time");
            List<Order> orders = orderService.list(queryWrapper);
            log.info("用户 {} 共有 {} 个订单", userId, orders.size());
            
            // 详细记录每个订单信息
            for (Order order : orders) {
                log.info("用户订单详情: ID={}, 订单号={}, 用户ID={}, 状态={}, 金额={}", 
                    order.getId(), order.getOrderNo(), order.getUserId(), 
                    order.getStatus(), order.getTotalAmount());
            }
            
            List<Map<String, Object>> resultList = orders.stream().map(order -> {
                Map<String, Object> item = new HashMap<>();
                item.put("id", order.getId());
                item.put("orderNo", order.getOrderNo());
                item.put("status", order.getStatus());
                item.put("totalAmount", order.getTotalAmount());
                item.put("payAmount", order.getPayAmount());
                item.put("discountAmount", order.getDiscountAmount());
                item.put("payType", order.getPayType());
                item.put("payTime", order.getPayTime());
                item.put("createTime", order.getCreateTime());
                item.put("itemCount", getOrderItemCount(order.getId())); // 商品数量
                item.put("items", getOrderItems(order.getId())); // 查询订单明细
                return item;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("orders", resultList);
            data.put("total", resultList.size());
            data.put("userId", userId);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户订单失败", e);
            return Result.error("获取用户订单失败");
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/orders/detail")
    public Result<Map<String, Object>> getOrderDetail(
            @RequestHeader("Authorization") String token,
            @RequestParam("orderId") Long orderId) {
        
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }
        
        try {
            log.info("查询订单详情: orderId={}, userId={}", orderId, userId);
            
            // 查询订单
            Order order = orderService.getById(orderId);
            if (order == null) {
                return Result.notFound("订单不存在");
            }
            
            // 验证订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                return Result.unauthorized("无权访问此订单");
            }
            
            // 构建订单详情
            Map<String, Object> orderDetail = new HashMap<>();
            orderDetail.put("id", order.getId());
            orderDetail.put("orderNo", order.getOrderNo());
            orderDetail.put("status", order.getStatus());
            orderDetail.put("totalAmount", order.getTotalAmount());
            orderDetail.put("payAmount", order.getPayAmount());
            orderDetail.put("discountAmount", order.getDiscountAmount());
            orderDetail.put("payType", order.getPayType());
            orderDetail.put("createTime", order.getCreateTime());
            orderDetail.put("payTime", order.getPayTime());
            
            // 查询订单商品明细
            log.info("开始查询订单 {} 的商品明细", orderId);
            List<Map<String, Object>> items = getOrderItems(orderId);
            log.info("订单 {} 的商品明细查询结果: {}", orderId, items);
            orderDetail.put("items", items);
            
            // TODO: 查询收货地址
            orderDetail.put("address", null);
            
            log.info("订单详情查询成功: {}", orderDetail);
            return Result.success(orderDetail);
            
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return Result.error("获取订单详情失败");
        }
    }
    
    /**
     * 支付订单
     */
    @PostMapping("/orders/pay")
    public Result<Map<String, Object>> payOrder(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        String orderNo = (String) request.get("orderNo");
        if (orderNo == null) {
            return Result.badRequest("订单编号不能为空");
        }
        
        try {
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            Order order = orderService.getOne(queryWrapper);
            
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 验证订单状态：只有pending状态才能支付
            if (order.getStatus() == null || !"pending".equals(order.getStatus())) {
                return Result.badRequest("订单状态不正确，只有待付款订单才能支付");
            }
            
            // 更新订单状态为已支付
            order.setStatus("paid");
            order.setPayTime(new Date());
            boolean success = orderService.updateById(order);
            
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", orderNo);
            data.put("status", "paid");
            data.put("message", success ? "支付成功" : "支付失败");
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("支付订单失败", e);
            return Result.error("支付失败");
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/orders/cancel")
    public Result<Map<String, Object>> cancelOrder(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        String orderNo = (String) request.get("orderNo");
        if (orderNo == null) {
            return Result.badRequest("订单编号不能为空");
        }
        
        try {
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            Order order = orderService.getOne(queryWrapper);
            
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 验证订单状态：只有pending状态才能取消
            if (order.getStatus() == null || !"pending".equals(order.getStatus())) {
                return Result.badRequest("订单状态不正确，只有待付款订单才能取消");
            }
            
            // 更新订单状态为已取消
            order.setStatus("cancelled");
            boolean success = orderService.updateById(order);
            
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", orderNo);
            data.put("status", "cancelled");
            data.put("message", success ? "订单已取消" : "取消失败");
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return Result.error("取消失败");
        }
    }
    
    /**
     * 批量删除收藏
     */
    @PostMapping("/collections/batchRemove")
    public Result<Map<String, Object>> batchRemoveCollections(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> items = (List<Map<String, Object>>) request.get("items");
            if (items == null || items.isEmpty()) {
                return Result.badRequest("删除项目不能为空");
            }

            int successCount = 0;
            int failCount = 0;

            for (Map<String, Object> item : items) {
                try {
                    Long entityId = Long.valueOf(item.get("entityId").toString());
                    String entityType = item.get("entityType").toString();

                    QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("user_id", userId);
                    queryWrapper.eq("entity_id", entityId);
                    queryWrapper.eq("entity_type", entityType);

                    boolean success = userCollectionService.remove(queryWrapper);
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("删除收藏项失败: {}", item, e);
                    failCount++;
                }
            }

            Map<String, Object> data = new HashMap<>();
            data.put("successCount", successCount);
            data.put("failCount", failCount);
            data.put("message", String.format("成功删除%d个，失败%d个", successCount, failCount));

            return Result.success(data);
        } catch (Exception e) {
            log.error("批量删除收藏失败", e);
            return Result.error("批量删除失败");
        }
    }
    
    // ==================== 用户地址功能接口 ====================
    
    /**
     * 获取用户地址列表
     */
    @GetMapping("/addresses")
    public Result<Map<String, Object>> getUserAddresses(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                       .orderByDesc("is_default")
                       .orderByDesc("create_time");
            List<UserAddress> addresses = userAddressService.list(queryWrapper);

            Map<String, Object> data = new HashMap<>();
            data.put("addresses", addresses);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户地址失败", e);
            return Result.error("获取用户地址失败");
        }
    }
    
    /**
     * 删除地址
     */
    @PostMapping("/addresses/delete")
    public Result<Map<String, Object>> deleteAddress(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        Long id = Long.valueOf(request.get("id").toString());
        if (id == null) {
            return Result.badRequest("地址ID不能为空");
        }

        try {
            QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            queryWrapper.eq("user_id", userId);
            boolean success = userAddressService.remove(queryWrapper);

            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", id);
                data.put("message", "删除成功");
                return Result.success(data);
            } else {
                return Result.error("删除失败或地址不存在");
            }
        } catch (Exception e) {
            log.error("删除地址失败", e);
            return Result.error("删除失败");
        }
    }
    
    /**
     * 设置默认地址
     */
    @PostMapping("/addresses/setDefault")
    public Result<Map<String, Object>> setDefaultAddress(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        Long id = Long.valueOf(request.get("id").toString());
        if (id == null) {
            return Result.badRequest("地址ID不能为空");
        }

        try {
            // 1. 将该用户所有地址设为非默认
            UserAddress updateNonDefault = new UserAddress();
            updateNonDefault.setIsDefault(0);
            QueryWrapper<UserAddress> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("user_id", userId);
            userAddressService.update(updateNonDefault, updateWrapper);

            // 2. 将指定地址设为默认
            UserAddress address = userAddressService.getById(id);
            if (address == null || !address.getUserId().equals(userId)) {
                return Result.notFound("地址不存在或无权操作");
            }
            address.setIsDefault(1);
            boolean success = userAddressService.updateById(address);

            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", id);
                data.put("message", "设置成功");
                return Result.success(data);
            } else {
                return Result.error("设置失败");
            }
        } catch (Exception e) {
            log.error("设置默认地址失败", e);
            return Result.error("设置失败");
        }
    }
    
    /**
     * 取消默认地址
     */
    @PostMapping("/addresses/cancelDefault")
    public Result<Map<String, Object>> cancelDefaultAddress(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        Long id = Long.valueOf(request.get("id").toString());
        if (id == null) {
            return Result.badRequest("地址ID不能为空");
        }

        try {
            // 检查地址是否存在且属于当前用户
            UserAddress address = userAddressService.getById(id);
            if (address == null || !address.getUserId().equals(userId)) {
                return Result.notFound("地址不存在或无权操作");
            }

            // 将该用户所有地址设为非默认
            UserAddress updateNonDefault = new UserAddress();
            updateNonDefault.setIsDefault(0);
            QueryWrapper<UserAddress> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("user_id", userId);
            boolean success = userAddressService.update(updateNonDefault, updateWrapper);

            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", id);
                data.put("message", "取消成功");
                return Result.success(data);
            } else {
                return Result.error("取消失败");
            }
        } catch (Exception e) {
            log.error("取消默认地址失败", e);
            return Result.error("取消失败");
        }
    }
    
    /**
     * 添加地址
     */
    @PostMapping("/addresses/add")
    public Result<Map<String, Object>> addAddress(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        try {
            UserAddress address = new UserAddress();
            address.setUserId(userId);
            address.setReceiver(request.get("receiver").toString());
            address.setPhone(request.get("phone").toString());
            address.setProvince(request.get("province").toString());
            address.setCity(request.get("city").toString());
            address.setDistrict(request.get("district").toString());
            address.setDetailAddress(request.get("detailAddress").toString());
            address.setIsDefault(Integer.valueOf(request.get("isDefault").toString()));
            address.setCreateTime(new Date());
            address.setUpdateTime(new Date());

            // 如果设置为默认地址，先将其他地址设为非默认
            if (address.getIsDefault() == 1) {
                UserAddress updateNonDefault = new UserAddress();
                updateNonDefault.setIsDefault(0);
                QueryWrapper<UserAddress> updateWrapper = new QueryWrapper<>();
                updateWrapper.eq("user_id", userId);
                userAddressService.update(updateNonDefault, updateWrapper);
            }

            boolean success = userAddressService.save(address);

            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", address.getId());
                data.put("message", "添加成功");
                return Result.success(data);
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加地址失败", e);
            return Result.error("添加失败");
        }
    }
    
    /**
     * 更新地址
     */
    @PutMapping("/addresses/update")
    public Result<Map<String, Object>> updateAddress(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        Long id = Long.valueOf(request.get("id").toString());
        if (id == null) {
            return Result.badRequest("地址ID不能为空");
        }

        try {
            // 检查地址是否存在且属于当前用户
            UserAddress existingAddress = userAddressService.getById(id);
            if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
                return Result.notFound("地址不存在或无权操作");
            }

            // 更新地址信息
            existingAddress.setReceiver(request.get("receiver").toString());
            existingAddress.setPhone(request.get("phone").toString());
            existingAddress.setProvince(request.get("province").toString());
            existingAddress.setCity(request.get("city").toString());
            existingAddress.setDistrict(request.get("district").toString());
            existingAddress.setDetailAddress(request.get("detailAddress").toString());
            existingAddress.setIsDefault(Integer.valueOf(request.get("isDefault").toString()));
            existingAddress.setUpdateTime(new Date());

            // 如果设置为默认地址，先将其他地址设为非默认
            if (existingAddress.getIsDefault() == 1) {
                UserAddress updateNonDefault = new UserAddress();
                updateNonDefault.setIsDefault(0);
                QueryWrapper<UserAddress> updateWrapper = new QueryWrapper<>();
                updateWrapper.eq("user_id", userId);
                updateWrapper.ne("id", id);
                userAddressService.update(updateNonDefault, updateWrapper);
            }

            boolean success = userAddressService.updateById(existingAddress);

            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", id);
                data.put("message", "更新成功");
                return Result.success(data);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新地址失败", e);
            return Result.error("更新失败");
        }
    }
    
    /**
     * 获取地址详情
     */
    @GetMapping("/addresses/{id}")
    public Result<Map<String, Object>> getAddressDetail(
            @RequestHeader("Authorization") String token,
            @PathVariable Long id) {

        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未授权访问");
        }

        try {
            UserAddress address = userAddressService.getById(id);
            if (address == null || !address.getUserId().equals(userId)) {
                return Result.notFound("地址不存在或无权访问");
            }

            Map<String, Object> data = new HashMap<>();
            data.put("id", address.getId());
            data.put("receiver", address.getReceiver());
            data.put("phone", address.getPhone());
            data.put("province", address.getProvince());
            data.put("city", address.getCity());
            data.put("district", address.getDistrict());
            data.put("detailAddress", address.getDetailAddress());
            data.put("isDefault", address.getIsDefault());
            data.put("createTime", address.getCreateTime());
            data.put("updateTime", address.getUpdateTime());

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取地址详情失败", e);
            return Result.error("获取地址详情失败");
        }
    }
    
    // ==================== 用户统计功能接口 ====================
    
    /**
     * 获取用户统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getUserStats(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            // 统计收藏数量
            QueryWrapper<UserCollection> collectionQuery = new QueryWrapper<>();
            collectionQuery.eq("user_id", userId);
            long collectionCount = userCollectionService.count(collectionQuery);

            // 统计订单数量
            QueryWrapper<Order> orderQuery = new QueryWrapper<>();
            orderQuery.eq("user_id", userId);
            long orderCount = orderService.count(orderQuery);

            Map<String, Object> data = new HashMap<>();
            data.put("courseCount", 0); // 待实现
            data.put("acupointCount", 0); // 待实现
            data.put("orderCount", orderCount);
            data.put("learnDays", 0); // 待实现
            data.put("totalStudyTime", 0); // 待实现
            data.put("points", 0); // 待实现

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户统计失败", e);
            return Result.error("获取用户统计失败");
        }
    }
    
    /**
     * 获取用户课程列表
     */
    @GetMapping("/courses")
    public Result<Map<String, Object>> getUserCourses(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            // TODO: 实际应该从数据库获取用户已购买/已学习的课程数据
            Map<String, Object> data = new HashMap<>();
            data.put("courses", new Object[]{});
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户课程失败", e);
            return Result.error("获取用户课程失败");
        }
    }
    
    /**
     * 获取用户钱包信息
     */
    @GetMapping("/wallet")
    public Result<Map<String, Object>> getUserWallet(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            // TODO: 实际应该从数据库获取用户钱包数据
            Map<String, Object> data = new HashMap<>();
            data.put("balance", 0.00);
            data.put("points", 0);
            data.put("vipLevel", "普通会员");
            data.put("vipExpireTime", "");
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户钱包失败", e);
            return Result.error("获取用户钱包失败");
        }
    }
    
    // ==================== 积分功能接口 ====================
    
    /**
     * 获取用户积分信息
     */
    @GetMapping("/points")
    public Result<Map<String, Object>> getUserPoints(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            // TODO: 实际应该从数据库获取用户积分数据
            Map<String, Object> data = new HashMap<>();
            data.put("totalPoints", 0);
            data.put("availablePoints", 0);
            data.put("usedPoints", 0);
            
            // 模拟积分历史记录
            List<Map<String, Object>> pointsHistory = new ArrayList<>();
            Map<String, Object> record1 = new HashMap<>();
            record1.put("id", 1L);
            record1.put("type", "checkin");
            record1.put("points", 10);
            record1.put("description", "每日签到");
            record1.put("time", new Date().toString());
            record1.put("status", "success");
            pointsHistory.add(record1);
            
            data.put("pointsHistory", pointsHistory);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户积分失败", e);
            return Result.error("获取用户积分失败");
        }
    }
    
    /**
     * 用户签到
     */
    @PostMapping("/points/checkin")
    public Result<Map<String, Object>> userCheckin(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            // TODO: 实际应该检查是否已签到，并添加积分记录
            Map<String, Object> data = new HashMap<>();
            data.put("points", 10);
            data.put("message", "签到成功，获得10积分");
            return Result.success(data);
        } catch (Exception e) {
            log.error("用户签到失败", e);
            return Result.error("签到失败");
        }
    }
    
    /**
     * 积分兑换
     */
    @PostMapping("/points/exchange")
    public Result<Map<String, Object>> exchangePoints(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            Integer points = Integer.valueOf(request.get("points").toString());
            Integer amount = Integer.valueOf(request.get("amount").toString());
            
            // TODO: 实际应该检查积分余额，并执行兑换逻辑
            Map<String, Object> data = new HashMap<>();
            data.put("points", points);
            data.put("amount", amount);
            data.put("message", "兑换成功");
            return Result.success(data);
        } catch (Exception e) {
            log.error("积分兑换失败", e);
            return Result.error("兑换失败");
        }
    }
    
    // ==================== 会员功能接口 ====================
    
    /**
     * 获取用户会员信息
     */
    @GetMapping("/membership")
    public Result<Map<String, Object>> getUserMembership(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            // TODO: 实际应该从数据库获取用户会员数据
            Map<String, Object> data = new HashMap<>();
            data.put("level", "bronze");
            data.put("levelName", "青铜会员");
            data.put("points", 0);
            data.put("expireTime", "");
            
            // 会员权益
            List<String> benefits = new ArrayList<>();
            benefits.add("基础课程学习");
            benefits.add("社区交流");
            benefits.add("每日签到奖励");
            data.put("benefits", benefits);
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户会员信息失败", e);
            return Result.error("获取会员信息失败");
        }
    }
    
    /**
     * 升级会员
     */
    @PostMapping("/membership/upgrade")
    public Result<Map<String, Object>> upgradeMembership(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            String targetLevel = request.get("targetLevel").toString();
            
            // TODO: 实际应该检查升级条件，并执行升级逻辑
            Map<String, Object> data = new HashMap<>();
            data.put("newLevel", targetLevel);
            data.put("message", "升级成功");
            return Result.success(data);
        } catch (Exception e) {
            log.error("会员升级失败", e);
            return Result.error("升级失败");
        }
    }
    
    /**
     * 购买会员套餐
     */
    @PostMapping("/membership/purchase")
    public Result<Map<String, Object>> purchaseMembership(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("未授权访问");
        }
        
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("用户ID无效");
        }
        
        try {
            String planType = request.get("planType").toString();
            Double amount = Double.valueOf(request.get("amount").toString());
            
            // TODO: 实际应该处理支付逻辑，并更新会员信息
            Map<String, Object> data = new HashMap<>();
            data.put("planType", planType);
            data.put("amount", amount);
            data.put("message", "购买成功");
            return Result.success(data);
        } catch (Exception e) {
            log.error("购买会员套餐失败", e);
            return Result.error("购买失败");
        }
    }
    
    /**
     * 从token中解析用户ID
     */
    private Long getUserIdFromToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("Token格式不正确: {}", token);
            return null;
        }
        
        try {
            String tokenValue = token.substring(7);
            log.info("正在解析token: {}", tokenValue);
            
            // 通过LoginUserService获取用户信息
            Map<String, Object> userInfo = loginUserService.getUserByToken(tokenValue);
            
            if (userInfo == null) {
                log.warn("Token无效或已过期: {}", tokenValue);
                return null;
            }
            
            log.info("Token解析成功，用户信息: {}", userInfo);
            
            // 从用户信息中获取用户ID
            Object userIdObj = userInfo.get("id");
            log.info("从用户信息中获取的ID对象: {} (类型: {})", userIdObj, userIdObj != null ? userIdObj.getClass().getSimpleName() : "null");
            
            if (userIdObj instanceof Long) {
                Long userId = (Long) userIdObj;
                log.info("解析得到的用户ID: {}", userId);
                return userId;
            } else if (userIdObj instanceof Integer) {
                Long userId = ((Integer) userIdObj).longValue();
                log.info("解析得到的用户ID: {}", userId);
                return userId;
            } else if (userIdObj instanceof String) {
                Long userId = Long.valueOf((String) userIdObj);
                log.info("解析得到的用户ID: {}", userId);
                return userId;
            } else {
                log.warn("用户ID类型不正确: {}", userIdObj);
                return null;
            }
            
        } catch (Exception e) {
            log.error("解析token失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 获取订单商品数量
     */
    private Integer getOrderItemCount(Long orderId) {
        try {
            // 首先尝试从order_item表查询
            QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            long count = orderItemService.count(queryWrapper);
            
            if (count > 0) {
                return Math.toIntExact(count);
            }
            
            // 如果order_item表没有数据，检查order表是否有productid
            Order order = orderService.getById(orderId);
            if (order != null && order.getProductid() != null) {
                return 1; // 从order表获取到商品，数量为1
            }
            
            // 如果都没有数据，返回模拟数据的数量
            List<Map<String, Object>> mockItems = getMockOrderItems(orderId);
            return mockItems.size();
        } catch (Exception e) {
            log.error("获取订单商品数量失败: {}", e.getMessage());
            // 出错时返回模拟数据的数量
            List<Map<String, Object>> mockItems = getMockOrderItems(orderId);
            return mockItems.size();
        }
    }
    
    /**
     * 获取订单商品明细
     */
    private List<Map<String, Object>> getOrderItems(Long orderId) {
        try {
            // 首先尝试从order_item表查询
            QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            List<OrderItem> orderItems = orderItemService.list(queryWrapper);
            
            List<Map<String, Object>> items = new ArrayList<>();
            
            if (!orderItems.isEmpty()) {
                // 如果order_item表有数据，使用order_item数据
                log.info("从order_item表获取订单 {} 的商品数据", orderId);
                for (OrderItem item : orderItems) {
                    Map<String, Object> itemMap = new HashMap<>();
                    itemMap.put("id", item.getId());
                    itemMap.put("name", item.getItemName());
                    itemMap.put("price", item.getPrice());
                    itemMap.put("quantity", item.getQuantity());
                    itemMap.put("totalPrice", item.getPrice().multiply(new java.math.BigDecimal(item.getQuantity())));
                    
                    // 根据商品类型和ID获取商品图片
                    String imageUrl = getProductImage(item.getEntityType(), item.getEntityId());
                    itemMap.put("image", imageUrl);
                    
                    items.add(itemMap);
                }
            } else {
                // 如果order_item表没有数据，尝试从order表的productid获取
                log.info("order_item表为空，尝试从order表获取订单 {} 的商品数据", orderId);
                items = getOrderItemsFromOrderTable(orderId);
            }
            
            // 如果还是没有数据，使用模拟数据
            if (items.isEmpty()) {
                log.info("订单 {} 没有商品数据，使用模拟数据", orderId);
                items = getMockOrderItems(orderId);
            }
            
            return items;
        } catch (Exception e) {
            log.error("获取订单商品明细失败: {}", e.getMessage());
            // 出错时也返回模拟数据
            return getMockOrderItems(orderId);
        }
    }
    
    /**
     * 从order表的productid字段获取商品信息
     */
    private List<Map<String, Object>> getOrderItemsFromOrderTable(Long orderId) {
        try {
            // 查询订单信息
            Order order = orderService.getById(orderId);
            if (order == null) {
                log.warn("订单 {} 不存在", orderId);
                return new ArrayList<>();
            }
            
            // 获取productid
            Integer productId = order.getProductid();
            if (productId == null) {
                log.warn("订单 {} 没有productid", orderId);
                return new ArrayList<>();
            }
            
            // 查询商品信息
            Product product = productService.getById(productId.longValue());
            if (product == null) {
                log.warn("商品 {} 不存在", productId);
                return new ArrayList<>();
            }
            
            // 构建商品信息
            List<Map<String, Object>> items = new ArrayList<>();
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("id", productId);
            itemMap.put("name", product.getName());
            itemMap.put("price", product.getPrice());
            itemMap.put("quantity", 1); // 默认数量为1
            itemMap.put("totalPrice", product.getPrice());
            itemMap.put("image", product.getCover() != null ? product.getCover() : "https://img.icons8.com/color/300x300/package.png");
            
            items.add(itemMap);
            log.info("从order表成功获取订单 {} 的商品信息: {}", orderId, itemMap);
            
            return items;
        } catch (Exception e) {
            log.error("从order表获取商品信息失败: {}", e.getMessage());
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取模拟订单商品数据
     */
    private List<Map<String, Object>> getMockOrderItems(Long orderId) {
        List<Map<String, Object>> items = new ArrayList<>();
        
        // 根据订单ID返回不同的模拟商品数据
        if (orderId == 1) {
            Map<String, Object> item1 = new HashMap<>();
            item1.put("id", 1);
            item1.put("name", "中医穴位按摩仪");
            item1.put("price", new java.math.BigDecimal("199.00"));
            item1.put("quantity", 1);
            item1.put("totalPrice", new java.math.BigDecimal("199.00"));
            item1.put("image", "https://img.icons8.com/color/300x300/massage.png");
            items.add(item1);
        } else if (orderId == 2) {
            Map<String, Object> item1 = new HashMap<>();
            item1.put("id", 2);
            item1.put("name", "艾灸条套装");
            item1.put("price", new java.math.BigDecimal("149.50"));
            item1.put("quantity", 2);
            item1.put("totalPrice", new java.math.BigDecimal("299.00"));
            item1.put("image", "https://img.icons8.com/color/300x300/incense.png");
            items.add(item1);
        } else {
            // 默认商品
            Map<String, Object> item1 = new HashMap<>();
            item1.put("id", 1);
            item1.put("name", "中医养生商品");
            item1.put("price", new java.math.BigDecimal("199.00"));
            item1.put("quantity", 1);
            item1.put("totalPrice", new java.math.BigDecimal("199.00"));
            item1.put("image", "https://img.icons8.com/color/300x300/package.png");
            items.add(item1);
        }
        
        return items;
    }
    
    /**
     * 获取商品图片
     */
    private String getProductImage(Object entityType, Long entityId) {
        try {
            // 根据商品类型获取不同的图片
            if (entityType != null && entityId != null) {
                String typeStr = entityType.toString();
                if ("product".equals(typeStr)) {
                    // 商品类型，可以查询商品表获取图片
                    return "https://img.icons8.com/color/300x300/package.png";
                } else if ("course".equals(typeStr)) {
                    // 课程类型
                    return "https://img.icons8.com/color/300x300/book.png";
                } else if ("acupoint".equals(typeStr)) {
                    // 穴位类型
                    return "https://img.icons8.com/color/300x300/medical.png";
                }
            }
            
            // 默认图片
            return "https://img.icons8.com/color/300x300/package.png";
        } catch (Exception e) {
            log.error("获取商品图片失败: {}", e.getMessage());
            return "https://img.icons8.com/color/300x300/package.png";
        }
    }
}
